<?php
// +----------------------------------------------------------------------
// | APP版本
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------
namespace app\event\app;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\app\AppTaskOrder as AppTaskOrderModel;
use app\model\app\AppTaskPz as AppTaskPzModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\ucenter\UserTask as UserTaskModel;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use think\File;
use yicmf\tools\FlowSn;
use yicmf\tools\HttpService;
use app\model\app\AppTaskBb as AppTaskBbModel;
use app\model\app\AppTask as AppTaskModel;

class Tui extends Base
{


    protected $domain = 'https://dt.bd.cn';

    protected $headers = ['xdt-apikey' => 'k8PwKSwpQtpXDf4F'];


    public function getAllTask()
    {
        $re = HttpService::request($this->domain . '/wapi/process/list_app', [], 'GET', $this->headers);
        foreach ($re['content']['data'] as $index => $datum) {
            $insert['tui_id'] = $datum['id'];
            $insert['name'] = $datum['name'];
            $insert['image'] = $datum['image'];
            $insert['tui_status'] = $datum['status'];
            $insert['bb_zd'] = $datum['bb_zd'];
            $insert['dt_type'] = $datum['dt_type'];
            $insert['rw_notice'] = $datum['rw_notice'];
            $insert['has_qr'] = $datum['has_qr'];
            $insert['update_time'] = $datum['up_time'];
            $insert['create_time'] = $datum['created'];
            $insert['check_time'] = time_format('1 hour');
            if (!AppTaskModel::where('tui_id', $insert['tui_id'])->count()) {
                AppTaskModel::create($insert);
            }
        }
    }


    public function getTaskInfo()
    {

        try {
            $task = AppTaskModel::where('tui_status', 1)
                ->whereTime('check_time', '<', '2 hour')
                ->find();
            if ($task) {

                $task['check_time'] = time_format('6 hour');
                $re = HttpService::request($this->domain . '/wapi/process/list_apprw', ['appid' => $task['tui_id']], 'GET', $this->headers);
                $info = $re['content'];
                if ($info['code'] == 1) {
                    $task['jobs'] = $re['content']['data'];
                }
                $re = HttpService::request($this->domain . '/wapi/process/app_bm_info', ['appid' => $task['tui_id']], 'GET', $this->headers);
                if ($info['code'] == 1) {
                    $info = $re['content']['data'];
                    $task['bb_zds'] = $info['bb_zd'];
                    $task['select_bb_zd'] = $info['select_bb_zd'];
                    $task['bb_sm'] = $info['bb_sm'];
                    $task['pz_button_name'] = $info['pz_button_name'];
                    $task['tj_info_fileds'] = $info['tj_info_fileds'];
                    $task['team_bb_tip'] = $info['team_bb_tip'];
                    $task['ok_bb_tip'] = $info['ok_bb_tip'];
                    $task['bb_tj_tip'] = $info['bb_tj_tip'];
                    dump($info);
                    unset($info['bb_zd']);
                    unset($info['select_bb_zd']);
                    Log::write($info);
                }
                $task->save();
                dump($task->toArray());

            }
            Db::startTrans();

            Db::commit();
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;

    }


    /**
     * 申请推广
     * @param $time
     * @return array
     */
    public function apply($param, $user)
    {
        try {

            if (!$user) {
                throw new Exception('请先登录');
            }
            $task = AppTaskModel::where('status', 1)
                ->where('tui_status', 1)->where('is_online', 1)
                ->where('id', $param['app_task_id'])->find();
            if (!$task) {
                throw new Exception('任务暂时不支持申请');
            }
            $task['join_user'] = $task['join_user'] + 1;
            $task->save();
            $http_param['appid'] = $task['tui_id'];
            $http_param['wb_uid'] = $user['id'];
            $http_param['wb_bs'] = FlowSn::build('T');
            $http_param['data'] = [$param['data']];
            // 宝贝
            $re = HttpService::request($this->domain . '/wapi/process/save_bb', $http_param, 'POST', $this->headers);

            Log::write($re);
            //报备 1740148 1740149
            if ($re['content']['code'] != 1) {
                throw new Exception($re['content']['msg']);
            }

            Db::startTrans();

            $insert = [];
            if (isset($param['data']['name'])) {
                $insert['app_nickname'] = $param['data']['name'];
            }
            if (isset($param['data']['mobile_number'])) {
                $insert['app_mobile'] = $param['data']['mobile_number'];
            }
            $insert['bb_id'] = $re['content']['data']['id'];
            $insert['app_name'] = $task['name'];
            $insert['app_task_id'] = $task['id'];
            $insert['app_task_tui_id'] = $task['tui_id'];;
            $insert['user_id'] = $user['id'];
            $insert['wb_uid'] = $http_param['wb_uid'];
            $insert['wb_bs'] = $http_param['wb_bs'];
            $insert['post_data'] = [$param['data']];
            $insert['check_time'] = time_format();
            $insert['status'] = 3;//审核状态 1已通过 2不通过 3审核中
            $order = AppTaskBbModel::create($insert);
            if (!$order) {
                throw new Exception('任务保存失败');
            }

            // 新增任务
            $userTask = [];
            $userTask['task_id'] = 3;
            $userTask['relation_id'] = $order['bb_id'];
            $userTask['task_type'] = 28;
            $userTask['user_id'] = $user['id'];
            $userTask['agent_id'] = $user['agent_id'];
            $userTask['title'] = $task['name'];
//            $userTask['logo'] = $order['item_img'];
            $userTask['money'] = 0;
            $userTask['commission'] = 0;
            $userTask['task_no'] = $order['wb_bs'];
//            $userTask['end_time'] = time() + 30 * 86400;
            $userTask['step'] = 1;
            $userTask['submit_info'] = $order->toArray();
            $userTask['status'] = 1;
            $userTask = UserTaskModel::create($userTask);
            if (!$userTask) {
                throw new Exception('创建失败');
            }
            Db::commit();
            $rep = ['code' => 0, 'message' => $re['content']['msg'], 'data' => $re];
//            $rep = ['code' => 0, 'message' => 'chengg '];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage() . $e->getLine() . $e->getFile()];
        }
        return $rep;
    }

    protected function base64EncodeImage($image_file)
    {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }

    /**
     * 提交凭证
     * @param $time
     * @return array
     */
    public function subPz($param, $user)
    {
        try {
            if (!$user) {
                throw new Exception('请先登录');
            }
            $bb = AppTaskBbModel::where('status', 1)->where('id', $param['app_task_bb_id'])->find();

            if (!$bb) {
                throw new Exception('推广暂时不需要凭证');
            }

            $data = $param['data'];
            $sub_data = [];
            foreach ($data as $k => $v) {
                if ($v['type'] == 2) {
                    $files = [];
                    foreach ($v['data'] as $datum) {
                        $file = public_path() . $datum['save_path'] . $datum['save_name'];
                        $files[] = $this->_upload($file);
                    }
                    $sub_data[] = ['id' => $v['id'], 'data' => $files];
                } else {
                    $sub_data[] = ['id' => $v['id'], 'data' => $v['data']];
                }

            }

            $http_param['appid'] = $bb['app_task_tui_id'];
            $http_param['wb_uid'] = $user['id'];
            $http_param['wb_bs'] = FlowSn::build('PZ');
            $http_param['data'] = [
                [
                    'bb_id' => $bb['bb_id'],//1763484
                    'data' => $sub_data
                ]
            ];
            // 宝贝
            $re = HttpService::request($this->domain . '/wapi/process/save_pz', $http_param, 'POST', $this->headers);

            if ($re['content']['code'] != 1) {
                throw new Exception($re['content']['msg']);
            }
            $insert['pz_id'] = $re['content']['data']['id'];
            $insert['wb_bs'] = $http_param['wb_bs'];
            $insert['user_id'] = $http_param['wb_uid'];
            $insert['wb_uid'] = $http_param['wb_uid'];
            $insert['app_task_id'] = $http_param['appid'];
            $insert['appid'] = $http_param['appid'];
            $insert['check_time'] = time_format('120 minute');
            $insert['status'] = 3;
            AppTaskPzModel::create($insert);
            $rep = ['code' => 0, 'message' => '申请成功，请等待审核'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 上传图片
     * @param $time
     * @return array
     */
    public function upload($param, $user)
    {
        try {

            $http_param['file'] = '';
            $http_param['lx'] = 'img2';
            $re = HttpService::request($this->domain . '/wapi/process/up_file', $http_param, 'POST', $this->headers);
            $rep = ['code' => 0, 'data' => $re, 'message' => '申请成功，请等待审核'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 上传图片
     * @param $time
     * @return array
     */
    protected function _upload($file)
    {
//            $http_param['file'] = '';
        $http_param['file'] = $this->base64EncodeImage($file);
        $http_param['lx'] = 'img2';
        $re = HttpService::request($this->domain . '/wapi/process/up_file', $http_param, 'POST', $this->headers);
        if ($re['code'] == 200 && $re['content']['code'] == 1) {
            return $re['content']['data'];
        } else {
            throw new Exception('系统故障，稍后再试');
        }
    }

    /**
     * 获取报备信息
     * @param $time
     * @return array
     */
    public function getBb()
    {
        try {
            $bb = AppTaskBbModel::where('status', 3)->whereTime('check_time', '<', 'now')->find();
            if ($bb) {
                $re = HttpService::request($this->domain . '/wapi/process/detail_bb', ['appid' => $bb['app_task_tui_id'], 'wb_bs' => $bb['wb_bs']], 'GET', $this->headers);
                $info = $re['content'];
                if ($info['code'] == 1) {
                    $data = $re['content']['data'];
                    $data['bb_id'] = $data['id'];
                    $data['post_data'] = json_decode($data['post_data'], true);
                    $data['check_time'] = time_format('10 minute');
                    dump($data);
                    unset($data['id']);
                    unset($data['up_time']);
                    unset($data['created']);
                    Log::write($data);
                    $bb->save($data);
                } else {
                    Log::write('x111');
                }
            }
            Db::startTrans();

            Db::commit();
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    public function getBbs()
    {
        try {

            $re = HttpService::request($this->domain . '/wapi/process/list_bb', ['appid' => 855], 'GET', $this->headers);
            dump($re['content']);


            foreach ($re['content']['data'] as $index => $data) {

                $data['bb_id'] = $data['id'];
                if (!AppTaskBbModel::where('bb_id', $data['id'])->find()) {
                    $data['post_data'] = json_decode($data['post_data'], true);
                    $data['check_time'] = time_format('10 minute');
                    unset($data['id']);
                    unset($data['up_time']);
                    unset($data['status']);
                    unset($data['created']);

                    $order = AppTaskBbModel::create($data);

                    $userTask = [];
                    // 新增任务
                    $userTask['task_id'] = 3;
                    $userTask['relation_id'] = $order['bb_id'];
                    $userTask['task_type'] = 28;
                    $userTask['user_id'] = 16006;
                    $userTask['agent_id'] = 38;
                    $userTask['title'] = $data['app_name'];
//            $userTask['logo'] = $order['item_img'];
                    $userTask['money'] = 0;
                    $userTask['commission'] = 0;
                    $userTask['task_no'] = $order['wb_bs'];
//                    $userTask['end_time'] = time() + 30 * 86400;
                    $userTask['step'] = 1;
                    $userTask['submit_info'] = $order->toArray();
                    $userTask['status'] = 1;
                    $userTask = UserTaskModel::create($userTask);
                    if (!$userTask) {
                        throw new Exception('创建失败');
                    }
                    sleep(1);
                }


            }


            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 获取凭证更新信息
     * @param $time
     * @return array
     */
    public function getPz()
    {
        try {
            $pz = AppTaskPzModel::where('status', 3)->whereTime('check_time', '<', 'now')->find();
            if ($pz) {
                $re = HttpService::request($this->domain . '/wapi/process/detail_pz', ['appid' => $pz['app_task_id'], 'wb_bs' => $pz['wb_bs']], 'GET', $this->headers);
                $info = $re['content'];
                if ($info['code'] == 1) {
                    $data = $re['content']['data'];
                    $data['check_time'] = time_format('10 minute');
                    unset($data['id']);
                    unset($data['up_time']);
                    unset($data['created']);
                    Log::write($data);
                    $pz->save($data);
                } else {
                    Log::write('x111');
                }
            }
            Db::startTrans();

            Db::commit();
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 获取凭证更新信息
     * @param $time
     * @return array
     */
    public function getPzs()
    {
        try {

            $re = HttpService::request($this->domain . '/wapi/process/list_pz', ['appid' => 756], 'GET', $this->headers);

            dump($re);
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    public function getOrders($time = null)
    {
        try {
            $time = is_null($time) ? time() : $time;
            $param['created_start'] = time_format($time - 86400 * 7);
            $param['created_end'] = time_format($time);
            $param['created_sort'] = 'DESC';
            $param['limit'] = '200';
            // 宝贝
            $re = HttpService::request($this->domain . '/wapi/process/list_order', $param, 'GET', $this->headers);
            //报备 1740148 1740149
            if ($re['content'] != 200 && $re['content']['count'] > 0) {
                foreach ($re['content']['data'] as $key => $value) {
                    $insert = $value;
                    $insert['create_time'] = $insert['created'];
                    $insert['update_time'] = $insert['created'];
                    unset($insert['created']);
                    $this->_sysnOrder($insert);
                }
            }
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    public function getAppDetail($time = null)
    {
        try {
//            $param['appid'] = 855;
//            $re = HttpService::request($this->domain . '/wapi/process/detail_app', $param, 'GET', $this->headers);
//            dump($re);exit();
            $task = AppTaskModel::whereTime('check_time', '<', 'now')->where('is_recommend', 0)->where('is_online', 1)->find();
            if ($task) {
                $param['appid'] = $task['tui_id'];
                // 宝贝
                $re = HttpService::request($this->domain . '/wapi/process/detail_app', $param, 'GET', $this->headers);
                dump($re);
                //报备 1740148 1740149
                if ($re['content']['code'] == 1) {
                    $data = $re['content']['data'];
                    $data['tui_status'] = $data['status'];
                    $data['update_time'] = $data['up_time'];
                    $data['check_time'] = time_format('100 minute');
                    unset($data['id']);
                    unset($data['bb_zd']);
                    unset($data['up_time']);
                    unset($data['status']);
                    unset($data['created']);
                    $task->save($data);
                } else {
                    $task['check_time'] = time_format('100 minute');
                    $task->save();
                }
            }
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    private function _sysnOrder($insert)
    {
        $order = AppTaskOrderModel::where('order_sn', $insert['order_sn'])->find();
        if (!$order) {
            $order = AppTaskOrderModel::create($insert);
        }

        if ($order['status'] != $insert['status']) {
            $order['status'] = $insert['status'];
            $order->save();
        }
        $bb = AppTaskBbModel::where('bb_id', $order['bb_id'])->find();

        if ($bb) {
            $order['app_task_bb_id'] = $bb['id'];
            $bb['order_success'] = AppTaskOrderModel::where('bb_id', $order['bb_id'])->where('status', 1)->count();
            $bb['order'] = AppTaskOrderModel::where('bb_id', $order['bb_id'])->count();
            $bb['get_amount'] = AppTaskOrderModel::where('bb_id', $order['bb_id'])->where('status', 1)->sum('money');
            $bb->save();
            $appTask = AppTaskModel::where('id', $bb['app_task_id'])->find();
            if ($appTask) {
                $appTask['max_profit'] = AppTaskBbModel::where('app_task_id', $bb['app_task_id'])->max('get_amount');
                $appTask->save();
            }
        }
        if ($order['status'] == 1) {
            //订单状态 1成功 2失败
            $userTask = UserTaskModel::where('task_id', 3)
                ->where('task_type', 28)
                ->where('relation_id', $order['bb_id'])
                ->find();
            if ($userTask) {
                $order['user_task_id'] = $userTask['id'];
                $order['user_id'] = $userTask['user_id'];
                $order->save();
                $log = UserMoneyLogModel::where('user_id', $userTask['user_id'])->where('type', 52)
                    ->where('order_id', $order['order_sn'])
                    ->where('channel', 'rtb')->find();
                if (!$log && !empty($order['money']) && $order['money'] > 0) {
                    $user = UserModel::where('id', $userTask['user_id'])->find();
                    UserEvent::exhibitionIncome($user, $order['money'], $order['rw_name'], 52, $user['id'], $order['order_sn'], 0, 'rtb', 3);
                    $userTask['money'] = $userTask['money'] ? ($userTask['money'] + $order['money']) : $order['money'];
                    $userTask['commission'] = $userTask['commission'] ? ($userTask['commission'] + $order['money']) : $order['money'];
                    $userTask->save();
                    if ($bb) {
                        $appTask = AppTaskModel::where('id', $bb['app_task_id'])->find();
                        if ($appTask) {
                            $appTask['max_profit'] = AppTaskBbModel::where('app_task_id', $bb['app_task_id'])->max('get_amount');
                            $appTask->save();
                        }
                    }
                }
            }
        }
    }
}
